package com.it.gmall.cart.controller;

import com.it.gmall.cart.service.CartApiService;
import com.it.gmall.common.result.Result;
import com.it.gmall.common.util.AuthContextHolder;
import com.it.gmall.model.cart.CartInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RestController
@RequestMapping("/api/cart")
public class cartApiController {
    @Autowired
    private CartApiService cartApiService;

    /*加入购物车加和查分开写*/

    // 点击加入购物车-加
    @PostMapping("/addCart/{skuId}/{skuNum}")
    public void addToCart(@PathVariable long skuId, @PathVariable Integer skuNum, HttpServletRequest request){
        String userId = AuthContextHolder.getUserId(request);
        if(StringUtils.isEmpty(userId)){
            userId=AuthContextHolder.getUserTempId(request);
        }
        cartApiService.addCart(skuId,skuNum,userId);
    }

    // 点击加入购物车-查
    @GetMapping("/toCart/{skuId}")
    public CartInfo toCart(@PathVariable long skuId){
        return cartApiService.toCart(skuId);
    }

    // 点击去购物车结算
    @GetMapping("/cartList")
    public Result cartList(HttpServletRequest request){
        String userId = AuthContextHolder.getUserId(request);
        String userTempId = AuthContextHolder.getUserTempId(request);
        return Result.ok(cartApiService.goToCart(userId,userTempId));
    }

    // 点击取消选中和选中商品
    @GetMapping("/checkCart/{skuId}/{isChecked}")
    public Result checkCart(@PathVariable String skuId,@PathVariable Integer isChecked){

        // 根据用户id和商品id获取商品
        cartApiService.checkCart(skuId,isChecked);
        return Result.ok();
    }

    // 获取选中的商品清单
    @GetMapping("/getCheckedCartInfo")
    public List<CartInfo> getCheckedCartInfo(HttpServletRequest request){
        // 获取用户id
        String userId = AuthContextHolder.getUserId(request);
        // 获取选中商品并返回
        return cartApiService.getCheckedCartInfo(userId);
    }
}